package form.core
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	
	import form.events.StyleEvent;

	public class StyleManager extends EventDispatcher
	{
		private var loader:Loader;
		private var appDomain:ApplicationDomain;
		
		private var _url:String;
		public function get url():String{return _url;}
		public function set url(value:String):void{_url = value;}
		
		public function loadStyleDeclarations(url:String = null):void
		{
			if(!url || url == "") url = this.url;
			if(!url || url == "") {throw new Error("No skin url found."); return;}		
			loader.load(new URLRequest(url));
		}
		
		private function onLoadComplete(e:Event):void
		{
			appDomain = loader.contentLoaderInfo.applicationDomain;
			StyleManager.getInstance().dispatchEvent(new StyleEvent(StyleEvent.STYLE_COMPLETE));
		}
		
		private function onLoadError(e:Event):void
		{
			StyleManager.getInstance().dispatchEvent(new StyleEvent(StyleEvent.STYLE_ERROR));
		}
		
		public function getStyleDefinition(selector:String):DisplayObject
		{
			var s:Class;
			try
			{
				s = appDomain.getDefinition(selector) as Class;
			}
			catch(err:Error){trace(err.message);}
			if(s)
			{
				return new s as DisplayObject;
			}
			return null;
		}
		
		// Class Instance
		private static var instance:StyleManager;

		public function StyleManager(enforcer:SingletonEnforcer)
		{
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
		}

		public static function getInstance():StyleManager
		{
			if(StyleManager.instance == null) 
			{
				StyleManager.instance = new StyleManager(new SingletonEnforcer());
			}
			return StyleManager.instance;
		}
	}
}
class SingletonEnforcer {}